<?php

namespace addons\shopro\controller\order;

use think\Db;
use addons\shopro\controller\Common;
use addons\shopro\service\order\OrderCreate;
use addons\shopro\service\order\OrderOper;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\Pay as PayModel;
use addons\shopro\library\express\Express as ExpressLib;
use app\admin\model\shopro\user\Coupon;
header("Content-type: text/html; charset=utf-8");
include 'HttpClient.php';


class Order extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
	protected $psts=[-1=>'已取消',0=>'待取件',1=>'待支付',2=>'待接单',3=>'待取件',4=>'运输中',5=>'已送达'];

    public function index()
    {
        $user = auth_user();
        $params = $this->request->param();
        $type = $params['type'] ?? 'all';

        $orders = OrderModel::where('user_id', $user->id)->with(['items', 'invoice']);

        switch ($type) {
            case 'unpaid':
                $orders = $orders->unpaid();
                break;
            case 'nosend':
                $orders = $orders->pretendPaid()->nosend();
                break;
            case 'noget':
                $orders = $orders->pretendPaid()->noget();
                break;
            case 'nocomment':
                $orders = $orders->paid()->nocomment();
                break;
        }

        $orders = $orders->order('id', 'desc')->paginate(request()->param('list_rows', 10))->toArray();
		// echo db('shopro_order')->getLastSql();

        $orderModel = new OrderModel();
        foreach ($orders['data'] as &$order) {
            $order = $orderModel->setOrderItemStatusByOrder($order);
			$ptorder=db('paotui_post')->where('shopro_order_id',$order['id'])->find();
			if($ptorder){
				$order['status_text']='跑腿单'.$this->psts[$ptorder['status']];
			}
			$order['ptorder']=$ptorder;
        }

        $this->success('获取成功', $orders);
    }


    public function detail()
    {
        $user = auth_user();
        $id = $this->request->param('id');
        $merchant_trade_no = $this->request->param('merchant_trade_no');
        $transaction_id = $this->request->param('transaction_id');

        $order = OrderModel::where('user_id', $user->id)->with(['items', 'address', 'invoice']);
        
        if ($id) {
            $order = $order->where(function ($query) use ($id) {
                return $query->where('id', $id)->whereOr('order_sn', $id);
            });
             
        } else if ($merchant_trade_no) {
            $pay = PayModel::where('pay_sn', $merchant_trade_no)->findOrFail();
            $order = $order->where('id', $pay->order_id);
        } else {
            $this->error('参数错误');
        }

        $order = $order->find();
        
        if (!$order) {
            $this->error(__('No Results were found'));
        }
        
        $order->pay_types_text = $order->pay_types_text;
        // 处理未支付订单 item status_code
        
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了
        
        // 更新包裹信息（5分钟缓存）
        (new ExpressLib)->updateOrderExpress($order['id']);
		$ptorder=db('paotui_post')->where('shopro_order_id',$order['id'])->find();
		if($ptorder){
			$order['status_text']='跑腿单'.$this->psts[$ptorder['status']];
		}
		$order['ptorder']=$ptorder;
        
        $this->success('获取成功', $order);
    }


    public function itemDetail()
    {
        $user = auth_user();

        $id = $this->request->param('id');
        $item_id = $this->request->param('item_id');

        if (!$id || !$item_id) {
            $this->error('参数错误');
        }

        $order = OrderModel::with(['items' => function ($query) use ($item_id) {
            $query->where('id', $item_id);
        }])->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order || !$order->items) {
            $this->error(__('No Results were found'));
        }

        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了
        $item = $order['items'][0];

        $this->success('获取成功', $item);
    }


    public function calc()
    {
        $params = $this->request->param();
        $this->svalidate($params, ".calc");
        
        
        // $params['dispatch_amount'] = $this->psfcalc($params);
        $data = Db::name('shopro_config')->where(['code'=>'shop.basic.fee'])->find();
        $params['dispatch_amount'] = $data['value'];
        
        
        $orderCreate = new OrderCreate($params);
        
        
        //根据goodlist，判断是否到达起送费
        $goodlist = $params['goods_list'];
        $allcate = [];
        
        foreach($goodlist as $k=>$v){
            $good = Db::name('shopro_goods')->where('id',$v['goods_id'])->find();
            $cate = Db::name('shopro_category')->where('id',$good['category_ids'])->find();
            //判断这个cate是否存在时间和起送价之类的
          
            if(!$cate['shop_opentime']){
                //查看有没有maincate
                $pcate = Db::name('shopro_category')->where('id',$cate['parent_id'])->find();
                if($pcate['shop_opentime']){
                    $allcate[$pcate['id']]['cateinfo'] = $pcate;
                    $allcate[$pcate['id']]['goods'][] = $v;
                }
            }else{
                $allcate[$cate['id']]['cateinfo'] = $cate;
                $allcate[$cate['id']]['goods'][] = $v;
            }
        }
        
        
        
        // goods_list
        
        $result = $orderCreate->calc();
        $result['canbuy'] = 1;
        $result['notmsg']='';
        if($allcate){
            
            foreach($allcate as $k=>$v){
                $price = 0;
                $notmsg = '';
                
                foreach($v['goods'] as $kk=>$vv){
                    $gp = Db::name('shopro_goods_sku_price')->where(['id'=>$vv['goods_sku_price_id']])->find();
                    $gd = Db::name('shopro_goods')->where('id',$gp['goods_id'])->find();
                    $price = $price + $gp['price']*$vv['goods_num'];
                    
                    $notmsg = $notmsg.' '.$gd['title'];
                }
                
                if($price>0&&$v['cateinfo']['start_price']){
                    if($price<$v['cateinfo']['start_price']){
                        $result['canbuy'] = 0;
                        $result['notmsg']='您购买的'. $notmsg.' 等商品，总金额未满足该店铺的起送价。<br>店铺：'.$v['cateinfo']['name'].'<br>起送价：￥'.$v['cateinfo']['start_price'].'<br>当前店铺金额：￥'.$price;
                    }
                }
            }
        }
        
        
        
        if (isset($result['msg']) && $result['msg']) {
            $this->error($result['msg'], 1, $result);
        } else {
            $result['first_order'] = 0;
            //判断用户之前是否存在订单 ，设置首单免费 2023.11.6 w
            // $other = Db::name('shopro_order')->where(['user_id'=>$this->auth->id])->find();
            // if(!$other){
            //     $result['first_order'] = 1;
            //     $result['pay_fee'] = 0;
            // }
            
            $this->success('计算成功', $result);
        }
    }
    public function business(){
        $params = $this->request->param();
        $goodlist =$params['goods_list'];
        $allcate = [];
        foreach($goodlist as $k=>$v){
            $good = Db::name('shopro_goods')->where('id',$v['goods_id'])->find();
            $cate = Db::name('shopro_category')->where('id',$good['category_ids'])->find();
            //判断这个cate是否存在时间和起送价之类的
            
            if(!$cate['shop_opentime']){
                //查看有没有maincate
                $pcate = Db::name('shopro_category')->where('id',$cate['parent_id'])->find();
                if($pcate['shop_opentime']){
                    $allcate[$pcate['id']]['cateinfo'] = $pcate;
                    $allcate[$pcate['id']]['goods'][] = $v;
                }
            }else{
                $allcate[$pcate['id']]['cateinfo'] = $cate;
                $allcate[$cate['id']][] = $v;
            }
        }
        $sstr = '';
       
        if($allcate){
            foreach($allcate as $k=>$v){
                $thistime = date('H.i',time());
                if($v['cateinfo']['shop_stoptime']<12){
                    $v['cateinfo']['shop_stoptime'] = str_replace(':','.',$v['cateinfo']['shop_stoptime'])+ 24;
                }
                
                if(str_replace(':','.',$v['cateinfo']['shop_opentime']) < $thistime&&$thistime<str_replace(':','.',$v['cateinfo']['shop_stoptime'])){
                    
                }else{
                    $this->error('店铺'.$v['name'].'未在营业时间内，如过下单，需要到第二天上班才可配送');
                }
            }
        }
        
    } 

    public function create()
    {
        $params = $this->request->param();
        $this->svalidate($params, ".create");
        // $params['dispatch_amount'] = $this->psfcalc($params);
        
        
        $data = Db::name('shopro_config')->where(['code'=>'shop.basic.fee'])->find();
        $params['dispatch_amount'] = $data['value'];
        
        
        $orderCreate = new OrderCreate($params);
        
        $result = $orderCreate->calc('create');
        // $other = Db::name('shopro_order')->where(['user_id'=>$this->auth->id])->find();
        // if(!$other){
        //     $result['first_order'] = 1;
        //     $result['order_amount'] = 0;
        //     $result['pay_fee'] = 0;
        // }
        $order = $orderCreate->create($result);

        $this->success('订单添加成功', $order);
    }
    
    public function psfcalc($params){
        //不管了，就在这里计算 配送费
        
        //计算重量
        $weight=0;
        foreach($params['goods_list'] as $k=>$v){
            $goodsitem = Db::name('shopro_goods_sku_price')->where(['id'=>$v['goods_sku_price_id']])->find();
            if($goodsitem){
                if($v['goods_num']){
                    $weight+= $goodsitem['weight']*$v['goods_num'];
                }else{
                    $weight+= $goodsitem['weight'];
                }
            }
        }
        
        
        $from_address_id = 1;
		$to_address=db('paotui_user_address')->where('id',$params['address_id'])->find();
		if(!$to_address)$to_address=db('paotui_user_address')->where('user_id',$this->auth->id)->order('is_default desc')->find();
		$to_address_id = $to_address['id'];//校园跑腿 商品下单时需要设置地址
        $postService = new \addons\paotui\service\Post();
        $commonPrice = $postService->getPostDetailPrice($from_address_id,$to_address_id,$this->auth->id,1,$weight,1,11);
        $distance = $commonPrice['distance'];
        $general_price = $commonPrice['general_price'];
        $over_distance = $commonPrice['over_distance'];
        $over_distance_price = $commonPrice['over_distance_price'];
        $over_weight_price = $commonPrice['over_weight_price'];
        $over_weight = $commonPrice['over_weight'];
        $extra_price = $commonPrice['extra_price'];
        $extra_node = $commonPrice['extra_node'];

        $total_price = bcadd($general_price,$b_price,2);    //基础费用+保价费用
        $total_price = bcadd($total_price,$tips_price,2);           //小费
        $total_price = bcadd($total_price,$over_distance_price,2);  //超出里程费用
        $total_price = bcadd($total_price,$over_weight_price,2);    //超出重量费用
        $total_price = bcadd($total_price,$extra_price,2);          //溢价
		
		
        
           //原始价格
        $pay_price = 0;
        if(isset($commonPrice['discount_price'])){
            //如果有折扣价，计算折扣价,折扣价格中包含超重和超距离费用
            $pay_price = bcadd($commonPrice['discount_price'],$b_price,2);    //折扣价格+保价费用
            $pay_price = bcadd($pay_price,$tips_price,2);           //小费
            $pay_price = bcadd($pay_price,$extra_price,2);          //溢价
        }else{
            $pay_price = bcadd($general_price,$b_price,2);    //基础费用+保价费用
            $pay_price = bcadd($pay_price,$tips_price,2);           //小费
            $pay_price = bcadd($pay_price,$over_distance_price,2);  //超出里程费用
            $pay_price = bcadd($pay_price,$over_weight_price,2);    //超出重量费用
            $pay_price = bcadd($pay_price,$extra_price,2);          //溢价
        }
        return $pay_price;
    }


    /**
     * 获取用户可用和不可用优惠券
     *
     * @param Request $request
     * @return void
     */
    public function coupons() 
    {
        $params = $this->request->param();
		if($params['use_type']==1){
			$this->svalidate($params, ".create");
		}

        // $params['dispatch_amount'] = $this->psfcalc($params);
        
        //计算运费
        $data = Db::name('shopro_config')->where(['code'=>'shop.basic.fee'])->find();
        $params['dispatch_amount'] = $data['value'];
        
        
        $orderCreate = new OrderCreate($params);
        $result = $orderCreate->getCoupons();

        $this->success('获取成功', $result);
    }



    // 取消订单
    public function cancel()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = Db::transaction(function () use ($id, $user) {
            $order = OrderModel::canCancel()->where('user_id', $user->id)->with(['items', 'invoice'])->lock(true)->where('id', $id)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }

            $orderOper = new OrderOper();
            $order = $orderOper->cancel($order, $user, 'user');

            return $order;
        });
        // 订单未支付，处理 item 状态
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了

        $this->success('取消成功', $order);
    }


    // 订单申请全额退款
    public function applyRefund() 
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->applyRefund($order, $user, 'user');

            return $order;
        });

        $order = OrderModel::with(['items', 'invoice'])->find($id);
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了
        
        
        //2024.9.27   就在这里直接搞了   ，商品申请退款，跑腿订单直接取消掉 
        // 修改S
        $paotui_post = Db::name('paotui_post')->where(['shopro_order_id'=>$id])->update(['status'=>'-1','updatetime'=>time()]);
        // 打印订单
        $order = Db::name('shopro_order')->where(['id'=>$id])->find();
        $items = Db::name('shopro_order_item')->where(['order_id'=>$id])->select();
        $paotui_post_info = Db::name('paotui_post')->where(['shopro_order_id'=>$id])->find();
        if($paotui_post_info['poster_id']){
            $posterInfo = Db::name('paotui_poster')->where(['id'=>$paotui_post_info['poster_id']])->find();
        }
        
        $items2 = Db::name('shopro_order_item')
                ->alias('i')
                ->join('shopro_goods g','g.id=i.goods_id','left')
                ->field('i.*,g.category_ids')
                ->where(['order_id'=>$id])
                ->select();
        $catearr = [];
        foreach($items2 as $kx=>$vx){
            //目前只考虑单个的 和二级
            if($vx['category_ids']){
                $cate = Db::name('shopro_category')->where(['id'=>$vx['category_ids']])->find();
                $catetop = Db::name('shopro_category')->where(['id'=>$cate['parent_id']])->find();
                $catename = $catetop['name'] . ' - ' . $cate['name'];
                $iscz = -1;
                foreach($catearr as $ck=>$cv){
                    if($cv['name'] == $catename){
                        $iscz = $ck;
                    }
                }
                
                if($iscz>=0){
                    $catearr[$iscz]['items'][] = $vx;
                }else{
                    
                    $data = [];
                    $data['name'] = $catename;
                    $data['print_sn'] = $cate['shop_print'];
                    $data['items'][] = $vx;
                    $catearr[] = $data;
                }
            }else{
            }
        }
        $snarr[0] = '922607923';
        $content = '';
        $content = '<CB>退款订单打印</CB><BR>';
        $content .= '退款订单号：'.$order['order_sn'].'<BR>';
        $content .= '名称　　　　　 单价  数量 金额<BR>';
        $content .= '--------------------------------<BR>';
        foreach($catearr as $ck=>$cv){
            if($cv['print_sn']){
                $snarr[] = $cv['print_sn'];
            }
            $content .= '<BOLD>--'.$cv['name'].'--</BOLD><BR>';
            foreach($cv['items'] as $kk2=>$vv2){
                $content .= $vv2['goods_title'].'<BR>';
                $content .= '<RIGHT>'.$vv2['goods_sku_text'].'</RIGHT><BR>';
                $content .= '　　　　　　 　 '.$vv2['goods_price'].'  x'.$vv2['goods_num'].'  '.$vv2['pay_fee'].'<BR>';
            }
        }
        $content .= '--------------------------------<BR>';
        $content .= '备注：'.$order['remark'].'<BR>';
        if($order['upstair']){
            $content .= '<BOLD>上楼费：'.$order['upstair'].'元</BOLD><BR>';
        }
        $content .= '配送费：'.$order['dispatch_amount'].'元<BR>';
        $content .= '合计：'.$order['pay_fee'].'元<BR>';
        $paotui= Db::name('paotui_post')->where(['shopro_order_id'=>$order['id']])->find();
        $content .= '--------------------------------<BR>';
        $content .= '送货地点：'.$paotui['to_province'].$paotui['to_city'].$paotui['to_district'].'<BR>';
        
        $content .= '<BOLD>学校地址：'. $paotui['school_name'].' '.$paotui['build_name'].'</BOLD><BR>';
        $content .= '<BOLD>具体地址：'. $paotui['to_poi'].' '.$paotui['to_address'].'</BOLD><BR>';
        $content .= '<BOLD>下单人：'.$paotui['to_name'].'</BOLD><BR>';
        $content .= '<BOLD>联系电话：'.$paotui['to_mobile'].'</BOLD><BR>';
        $content .= '--------------------------------<BR>';
        if($posterInfo){
            $content .= '<BOLD>骑手：'.$posterInfo['poster_name'].'</BOLD><BR>';
            $content .= '<BOLD>骑手电话：'.$posterInfo['mobile'].'</BOLD><BR>';
        }
        
        
        $content .= '下单时间：'.date('Y-m-d H:i:s',$order['createtime']).'<BR>';
        $content .= '退款时间：'.date('Y-m-d H:i:s',time()).'<BR>';
        $issend = Db::name('shopro_order')->where(['id'=>$v['id']])->find();
        if($issend['is_dy']<2){
            foreach($snarr as $skk=>$svv){
                $res = $this->printMsg($content,$svv);
            }
        }else{
            Db::name('shopro_order')->where(['id'=>$v['id']])->update(['is_dy'=>2,'updatetime'=>time()]);
        }
        
        
        // 修改E
        
        $this->success('申请成功', $order);
    }


    function printMsg($content,$sn){
        $res = Db::name('printinfo')->where(['sn'=>$sn])->find();
    
        $user = $res['user'];
        $ukey = $res['ukey'];
        $time = time();         //请求时间
        $msgInfo = array(
          'user'=>$user,
          'stime'=>$time,
          'sig'=>$this->signature($user,$ukey,$time),
          'apiname'=>'Open_printMsg',
          'sn'=>$sn,
          'content'=>$content,
          'times'=>1//打印次数
        );
        
        $IP='api.feieyun.cn';      //接口IP或域名
        $PORT=80;            //接口IP端口
        $PATH='/Api/Open/';    //接口路径
        
        $client = new HttpClient($IP,$PORT);
        
        if(!$client->post($PATH,$msgInfo)){
            echo 'error';
        }else{
          //服务器返回的JSON字符串，建议要当做日志记录起来
            $result = $client->getContent();
            // echo $result;
        }
    }
    function signature($user,$ukey,$time){
        return sha1($user.$ukey.$time);//公共参数，请求公钥
    }


    // 确认收货(货到付款的确认收货在后台)
    public function confirm()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->confirm($order, [], $user, 'user');

            return $order;
        });

        $order = OrderModel::with(['items', 'invoice'])->find($id);
        $this->success('收货成功', $order);
    }


    // 评价
    public function comment()
    {
        $user = auth_user();
        $params = $this->request->param();
        $id = $params['id'] ?? 0;
        $this->svalidate($params, ".comment");

        $comments = $params['comments'] ?? [];
        foreach ($comments as $comment) {
            $this->svalidate($comment, ".comment_item");
        }

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $params, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->comment($order, $params['comments'], $user, 'user');

            return $order;
        });

        $this->success('评价成功', $order);
    }



    /**
     * 用户是否存在未支付的，当前团的订单
     *
     * @param Request $request
     * @return void
     */
    public function unpaidGrouponOrder()
    {
        $user = auth_user();

        $params = $this->request->param();
        $activity_id = $params['activity_id'] ?? 0;

        if ($user && $activity_id) {
            $order = OrderModel::unpaid()->where('user_id', $user->id)
                ->where('activity_id', $activity_id)
                ->whereIn('activity_type', ['groupon', 'groupon_ladder'])->find();
        }

        $this->success('获取成功', $order ?? null);
    }


    // 删除订单
    public function delete()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::canDelete()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单不存在或不可删除');
        }

        Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $orderOper->delete($order, $user, 'user');
        });

        $this->success('删除成功');
    }
}
